﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Xml;
using System.Text;

namespace Gollie
{
	public class WebReader
	{
		public static string ReadUrl(string url)
		{
			HttpWebResponse response = null;
			Stream receiveStream = null;
			StreamReader readStream = null;
			string htmlResponse = null;

			try
			{
				HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

				// Set some reasonable limits on resources used by this request
				request.Timeout = 10000;
				request.MaximumAutomaticRedirections = 4;
				request.MaximumResponseHeadersLength = 4;
				// Set credentials to use for this request.
				request.Credentials = CredentialCache.DefaultCredentials;

				response = (HttpWebResponse)request.GetResponse();

				// Get the stream associated with the response.
				receiveStream = response.GetResponseStream();

				// Pipes the stream to a higher level stream reader with the required encoding format. 
				readStream = new StreamReader(receiveStream, System.Text.Encoding.UTF8);

				htmlResponse = readStream.ReadToEnd();

				return htmlResponse;
			}
			catch (Exception e)
			{
				throw new Exception("Error reading url: " + e.Message);
			}
			finally
			{
				if (readStream != null)
					readStream.Close();

				if (response != null)
					response.Close();
			}
		}

		public static string ReadUrlWithPost(string url, string postText)
		{
			Stream dataStream = null;
			Stream responseStream = null; ;
			string stringResponse = null;

			try
			{
				WebRequest request = WebRequest.Create(url);
				request.Method = "POST";
				request.ContentType = "application/x-www-form-urlencoded";
				
				byte[] byteArray = Encoding.UTF8.GetBytes(postText);

				request.ContentLength = byteArray.Length;

				dataStream = request.GetRequestStream();

				// Write the data to the request stream.
				dataStream.Write(byteArray, 0, byteArray.Length);

				// Get the response.
				WebResponse response = request.GetResponse();

				responseStream = response.GetResponseStream();

				StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);

				stringResponse = reader.ReadToEnd();
			}
			catch (Exception e)
			{
				throw new Exception("Error reading url: " + e.Message);
			}
			finally
			{
				if (responseStream != null)
					responseStream.Close();

				if (dataStream != null)
					dataStream.Close();
			}

			return stringResponse;
		}
	}
}